import translateresult as fanyi
import mkdir as mkdir
# print(fanyi.translateresult(''))
import json
from string import Template
import re
import sys
import tkinter as tk
from tkinter import filedialog
from __init__ import Settings
from newrequest import htmls


def create__file(file_path,msg):
    f=open(file_path,"w+",encoding='utf-8')
    f.write(msg)
    f.close
		
def create__prefile(url,pathnum,Apilist):
    f = open(url+str(pathnum)+'.json', "w+", encoding='utf-8')
    f.write(json.dumps(Apilist))
    f.close
		
if __name__ == '__main__':
	settings=Settings()
	root = tk.Tk()
	root.withdraw()
	# settings.pathapis = input('正则apiurl')
	# indexjson=input('回车选择目标json文件')
	#Filepath = filedialog.askopenfilename() #获得选择好的文件
	#if bool(Filepath) == False:
	#	sys.exit(0)
	# outfolder=input('回车选择目标输出的文件地址')
	Folderpath = filedialog.askdirectory() #获得选择好的文件夹
	if bool(Folderpath) == False:
		sys.exit(0)
	if not bool(re.search('/EolinkerRobotization$',Folderpath.rstrip("\\"))):
		mkdir.mkdir(Folderpath+'/EolinkerRobotization')
	Folderpath=re.sub('/EolinkerRobotization$','',Folderpath,count=1)
	# isexist=os.path.exists('D:/desktop/钉钉/nailing-items/App.vue')
	for n in settings.fileurl:
		mkdir.mkdir(Folderpath+'/EolinkerRobotization/'+n)
	from oslist import PathName
	prefilepath=PathName(Folderpath+'/EolinkerRobotization/')
	pathname=prefilepath.default
	pathnum=prefilepath.num
	if pathname is not False:
			with open(Folderpath+"/EolinkerRobotization/prejson/"+pathname,"r") as load_pre:
					settings.prejson = json.load(load_pre)
					
	# print(prejson)
	# print('执行')
	# api 文件列表
	# with open(Filepath,"r") as load_f:
			# json_str = json.load(load_f)
	json_str = json.loads(htmls)["apiList"]
	# print(json_str)
	defaulttext = "import http from '@/api/http.js';\n"
	for n in json_str:
			if bool(re.search('\|',settings.pathapis)):
					for m in settings.pathapis.split('|'):
						if bool(re.match(r'.*?'+m+'/.+/.+', n["apiURI"])):
							settings.pathapi=m
							break
			elif bool(settings.pathapis):
				settings.pathapi=settings.pathapis
			else:
				for m in 'api|front'.split('|'):
					if bool(re.match(r'.*?'+m+'/.+/.+', n["apiURI"])):
						settings.pathapi=m
						break
			apiURI = settings.plusSlash + re.sub('\?.+','',re.match(r'.*?('+settings.pathapi+'.+)', n["apiURI"]).group(1),count=1) # 请求地址跟着? &=
			if apiURI not in settings.apiURIs:
					settings.apiURIs.append(apiURI)
			else:
					continue
			apiindex=re.match(r'.*?('+settings.pathapi+'/)(.+)/',n["apiURI"],re.I).group(2).lower() # api 后面跟着的目录 不是settings.apiname
			apikey = re.sub('\?.+','',re.match(r'.*/(.*?)$', n["apiURI"]).group(1),count=1)  # settings.apiname  删除 路径后跟着? 情况 区分大小写
			if apikey in settings.safeAreaList:
				apikey=re.sub('.',apikey[0:1].upper(),apikey,count=1)   # 目录不能 new..
			if apiindex in settings.safeAreaList:
				apiindex=re.sub('.',apiindex[0:1].upper(),apiindex,count=1)   #api名字不能new
			if apikey in settings.apiname:
					apiindexLower=apikey.lower()
					if settings.apiname[apikey]['change'] is not True:
							settings.apiname[apikey]['change'] = True
							settings.Apiobject[settings.apiname[apikey]['index']] = re.sub('const '+apikey+' =','const '+settings.apiname[apikey]['from']+apikey+' =',settings.Apiobject[settings.apiname[apikey]['index']], count=1)
							settings.Apilist = json.loads(re.sub('#'+apikey+'#','#'+settings.apiname[apikey]['from']+apikey+'#',json.dumps(settings.Apilist), count=1))
							settings.apikeys = json.loads(re.sub(r'\\t'+apikey+',//','#'+settings.apiname[apikey]['from']+apikey+',//',json.dumps(settings.apikeys), count=1).replace('#', '\\t'))
							if apiindexLower not in settings.changeapi:
									settings.changeapi[apiindexLower]=[]
							settings.changeapi[apiindexLower].append(settings.apiname[apikey]['from']+apikey)
					if apiindexLower not in settings.changeapi:
							settings.changeapi[apiindexLower] = []
					settings.changeapi[apiindexLower].append(re.match(r'.*?('+settings.pathapi+'/)(.+)/',n["apiURI"],re.I).group(2) + apikey)
					apikey = re.match(r'.*?('+settings.pathapi+'/)(.+)/',n["apiURI"],re.I).group(2)+apikey
			else:
					settings.apiname[apikey] = {}
					settings.apiname[apikey]['from'] = re.match(r'.*?('+settings.pathapi+'/)(.+)/',n["apiURI"],re.I).group(2)
					settings.apiname[apikey]['index'] = apiindex
					settings.apiname[apikey]['change'] = False
			if apikey not in settings.Apilist:
					settings.Apilist.append({'apikey':'#'+apikey+'#','from':re.sub('\?.+','',re.match(r'.*?('+settings.pathapi+'.+)', n["apiURI"]).group(1),count=1)})

			if apiindex not in settings.apikeys:
					settings.apikeys[apiindex]=[]
			settings.apikeys[apiindex].append('\u0009'+apikey + ',//' + n["apiName"])
			mjs = Template('const ${key} = (data) => http.${type}("${url}", data)')
			mjs = mjs.substitute(key=apikey, url=apiURI,type = settings.POST if n['apiRequestType']==0 else settings.GET)
			if apiindex not in settings.Apiobject:
					settings.Apiobject[apiindex]=defaulttext
			settings.Apiobject[apiindex]+= mjs + '\n'
	if not bool(len(settings.Apilist)):
		sys.exit(0)
	create__prefile(Folderpath+"/EolinkerRobotization/prejson/",pathnum,settings.Apilist)
	for n in settings.Apiobject:
			settings.Apiobject[n]+= 'export default{\n' + '\n'.join(settings.apikeys[n]) + '\n}'
			settings.ALLAPIimport += Template('import ${url} from "./${url}.js"').substitute(url = n if n!='index' else 'Indexs')+ '\n'
			settings.ALLAPIexport += Template(',${url}').substitute(url = n if n!='index' else 'Indexs')
			create__file(Folderpath+"/EolinkerRobotization/outtext/" + (n if n!='index' else 'Indexs') + ".js", settings.Apiobject[n])
	settings.ALLAPIexport+=')'

	settings.changetext+=json.dumps(settings.changeapi)
	if len(settings.prejson) == 0:
			settings.addtext = '\n初始化:\n'
	else:
			settings.addtext = '\n本次'+str(pathnum-1)+'修改新增:\n'
			settings.removetext = '\n本次'+str(pathnum-1)+'修改删除:\n'
	if pathnum==1 :
			settings.changetext+= settings.addtext+json.dumps(settings.Apilist)
	else:
			for n in settings.Apilist:
					if n not in settings.prejson:
							if n not in settings.addApilist:
									settings.addApilist.append(n)
			for n in settings.prejson:
					if n not in settings.Apilist:
							if n not in settings.removelist:
									settings.removelist.append(n)
			settings.changetext+= settings.addtext + json.dumps(settings.addApilist)
			settings.changetext+= settings.removetext + json.dumps(settings.removelist)
	f = open(Folderpath+'/EolinkerRobotization/outtext/index.js', "w+", encoding='utf-8')
	f.write(settings.ALLAPIimport+settings.ALLAPIexport)
	f.close

	md = open(Folderpath+'/EolinkerRobotization/outtext/README.md', "a", encoding='utf-8')
	md.write( re.sub('],', '],\n',settings.changetext, count=0))
	md.close

